package com.bluestone.assertor;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.spi.LoggingEvent;

import com.bluestone.util.Util;

public class HttpAssertor implements IAssertor{

	  static List<String> responses = new ArrayList();
	  static List<AssertorFilter> filters = new ArrayList();	  
	  
	public void addFilter(AssertorFilter filter) {
		this.filters.add(filter);
		
	}

	public void assertAfter() {
		// TODO Auto-generated method stub
		
	}

	public void assertBefore() {
		// TODO Auto-generated method stub
		
	}

	public boolean assertExecute(String method, Object obj) {
		if(method.equalsIgnoreCase("assertcleardata")){
			responses.clear();
			return true;
		}
		while(true){
			if(responses.size()>0){
				break;
			}
			try {
				this.wait(200);
				Util.getLogger().info("wait 200 for HttpAssertor");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(String temp:responses){
			if(method.equalsIgnoreCase("assertcontains")){
				if(String.class.isInstance(obj)){
					String str = Util.loadFile((String)obj);
					str = Util.getDynamicString(str);	
					str = str.replaceAll("\r", "");
					str = str.replaceAll("\n", "");
					temp = temp.replaceAll("\r", "");
					temp = temp.replaceAll("\n", "");
					Util.getLogger().info("file data:\r\n"+str);
					Util.getLogger().info("response data:\r\n"+temp);
					
					int pos = -1;
					
					while(true){
						pos = str.indexOf("{ignore}");
						if(pos<0){
							if(temp.indexOf(str)<0){
								Util.getLogger().error("cant find message \r\n"+str+"\r\n in \r\n"+temp);
								return false;  
							}else{
								break;
							}
							
						}else{
							String token = str.substring(0,pos);
							if(temp.indexOf(token)<0){
								Util.getLogger().error("cant find message \r\n"+token+"\r\n in \r\n"+temp);
								return false;  
							}
							str = str.substring(pos+8);
						}

					}
					return true;
				}
			}else if(method.equalsIgnoreCase("assertnotempty")){
				return true;
			}else if(method.equalsIgnoreCase("assertcleardata")){
				responses.clear();
				return true;
			}
		}
		return false;

	}

	public boolean isDefault() {
		// TODO Auto-generated method stub
		return false;
	}

	public void putData(Object obj) {
		boolean flag = true;
		for(AssertorFilter filter:filters){
			flag = filter.doFilter(obj);
			if(!flag){
				break;
			}
		}		
		if(flag && String.class.isInstance(obj)){
			responses.add((String)obj);
		}
		
	}

	public void setDefault(boolean isDefault) {
		// TODO Auto-generated method stub
		
	}

	public void setFilters(List filters) {
		this.filters = filters;
		
	}

	public void start() {
		// TODO Auto-generated method stub
		
	}

	public void stop() {
		// TODO Auto-generated method stub
		
	}

}
